package com.linked.store.thing.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.linked.store.thing.bean.param.AddThingParam;
import com.linked.store.thing.bean.param.ThingPageParam;
import com.linked.store.thing.bean.po.BrandInfoPO;
import com.linked.store.thing.bean.po.ThingImagesPO;
import com.linked.store.thing.bean.po.ThingInfoPO;
import com.linked.store.thing.bean.vo.ThingInfoVO;
import com.linked.store.thing.bean.vo.ThingPageVO;
import com.linked.store.thing.mapper.IBrandInfoMapper;
import com.linked.store.thing.mapper.IThingImagesMapper;
import com.linked.store.thing.mapper.IThingInfoMapper;
import com.linked.store.thing.service.IThingHandleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author :dbq
 * @date : 2023/3/17 14:02
 * @description : desc
 */
@Slf4j
@Service
public class ThingHandleServiceImpl implements IThingHandleService {

    private final ObjectMapper mapper;

    private final IThingInfoMapper thingInfoMapper;

    private final IThingImagesMapper thingImagesMapper;

    private final TransactionTemplate transactionTemplate;

    private final IBrandInfoMapper brandInfoMapper;

    private final StringRedisTemplate redisTemplate;

    @Autowired
    public ThingHandleServiceImpl(ObjectMapper mapper,
                                  IThingInfoMapper thingInfoMapper,
                                  IThingImagesMapper thingImagesMapper,
                                  TransactionTemplate transactionTemplate,
                                  StringRedisTemplate redisTemplate,
                                  IBrandInfoMapper brandInfoMapper) {
        this.mapper = mapper;
        this.thingInfoMapper = thingInfoMapper;
        this.thingImagesMapper = thingImagesMapper;
        this.transactionTemplate = transactionTemplate;
        this.brandInfoMapper = brandInfoMapper;
        this.redisTemplate = redisTemplate;
    }

    @Override
    public boolean addThingInfo(AddThingParam param) throws Exception {
        return transactionTemplate.execute(action -> {
            try {
                //查询品牌id
                BrandInfoPO brand = brandInfoMapper.findBrandByName(param.getBrandName());
                if (brand == null) {
                    brand = new BrandInfoPO();
                    brand.setBrandName(param.getBrandName());
                    int brandRet = brandInfoMapper.insert(brand);
                    if (brandRet <= 0) {
                        log.info("保存品牌失败！");
                        action.setRollbackOnly();
                        return false;
                    }
                }
                param.setBrandId(brand.getBrandId());
                ThingInfoPO temp = new ThingInfoPO(param);
                boolean thingRet = thingInfoMapper.insert(temp) > 0;
                if (!thingRet) {
                    log.info("保存物品失败！");
                    action.setRollbackOnly();
                    return false;
                }
                if (CollectionUtils.isEmpty(param.getThingImagsIds())) {
                    return true;
                }
                int imagesCount = thingImagesMapper.updateImagesToThings(temp.getThingId(), param.getThingImagsIds());
                if (imagesCount != param.getThingImagsIds().size()) {
                    log.info("保存物品图片失败！");
                    action.setRollbackOnly();
                    return false;
                }
                return true;
            } catch (Exception e) {
                log.error("添加物品异常", e);
                action.setRollbackOnly();
                return false;
            }
        });
    }

    @Override
    public List<ThingInfoVO> queryThingListByBoxId(String boxId) throws Exception {
        return thingInfoMapper.queryThingListByBoxId(boxId);
    }

    @Override
    public boolean uploadThingImage(ThingImagesPO thingImages) throws Exception {
        return thingImagesMapper.insert(thingImages) > 0;
    }

    @Override
    public IPage<ThingPageVO> queryThingPage(ThingPageParam param) {
        return thingInfoMapper.queryThingPage(param);
    }

    @Override
    public boolean reduceInventory(String goodsVersionId, int goodsCount) throws Exception {
        return thingInfoMapper.reduceInventory(goodsVersionId, goodsCount);
    }

    @Override
    public Integer findThingsCount(String goodsVersionId) {
        String redisKey = "ThingCount_" + goodsVersionId;
        if (redisTemplate.hasKey(redisKey)) {
            return Integer.parseInt(redisTemplate.opsForValue().get(redisKey));
        }
        QueryWrapper<ThingInfoPO> wrapper = new QueryWrapper<>();
        wrapper.eq("goods_version_id", goodsVersionId);
        ThingInfoPO tmp = thingInfoMapper.selectOne(wrapper);
        if (tmp != null) {
            redisTemplate.opsForValue().set(redisKey, String.valueOf(tmp.getThingCount()), 30, TimeUnit.MINUTES);
            return tmp.getThingCount();
        }
        return null;
    }
}
